package com.leetcode.algorithm.y22.m08.w1;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 2131. 连接两字母单词得到的最长回文串
 * 
 * https://leetcode.cn/problems/longest-palindrome-by-concatenating-two-letter-words/
 * 
 * @author jie.deng
 *
 */
class Question2131Solution01 {

	public int longestPalindrome(String[] words) {
		int cnt = 0;
		Map<String, Integer> map = new HashMap<>();
		Set<String> set = new HashSet<>();
		for (String word : words) {
			if (word.charAt(0) == word.charAt(1)) {
				if (!set.add(word)) {
					set.remove(word);
					cnt += 4;
				}
				continue;
			}
			String reversedWord = new String(new char[] { word.charAt(1), word.charAt(0) });
			Integer reversedWordCnt = map.get(reversedWord);
			if (reversedWordCnt != null) {
				cnt += 4;
				if (reversedWordCnt == 1) {
					map.remove(reversedWord);
				} else {
					map.put(reversedWord, reversedWordCnt - 1);
				}
			} else {
				Integer wordCnt = map.get(word);
				if (wordCnt == null) {
					map.put(word, 1);
				} else {
					map.put(word, wordCnt + 1);
				}
			}
		}
		if (set.size() > 0) {
			cnt += 2;
		}
		return cnt;
	}

}